import Vue from 'vue'
const api = window.$api.organization.post

let PostLoadTimer = null // 加载用户信息定时器
const PostLoadings = []  // 需要加载的用户信息
const Post = {
    namespaced: true,
    state:{
        updateList:{},
        map:{},
        one:{},
    },
    actions:{
        async getList({ commit,state},{companyId,isCache}){
            if(!state.updateList[companyId] || !isCache){
                state.updateList[companyId] = true
                var res = await api.getList({companyId})
                const data = res.data.data
                commit('SET_POST_MAP', {companyId,list:data})
            }
        },
        async load({ commit,state},{postIds,isCache}){
            postIds.forEach(postId => {
                if(!state.updateList[postId] || !isCache){
                    state.updateList[postId] = true
                    PostLoadings.push(postId)
                }
            })
            // 50ms 内只执行一次
            if(PostLoadings.length > 0 && !PostLoadTimer){
                PostLoadTimer = setTimeout(async ()=>{
                    const req = String(PostLoadings)
                    PostLoadings.length = 0
                    PostLoadTimer = null
                    const res = await api.gets(req)
                    const data = res.data.data
                    data.forEach(item=>{
                        commit('SET_POST_ONE', {entity:item,postId:item.f_PostId})
                    })
                }, 50)
            }
        }
    },
    mutations:{
        SET_POST_MAP: (state, payload) => {
            Vue.set(state.map,payload.companyId,payload.list)
        },
        SET_POST_ONE:(state, payload) => {
            Vue.set(state.one,payload.postId,payload.entity)
        },
    }
};

export default Post;